﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Spring.Objects.Factory.Config;
using Strongshell.Recoil.Core.Composition.Parsing.DependencyInjection;

namespace Strongshell.Recoil.Core.Composition.Parsing.Handlers
{
    public class NewExpressionHandler : IExpressionHandler
    {
        private readonly IObjectConfigurationRegistry objectConfigurationRegistry;
        private readonly IExpressionParser expressionParser;

        public NewExpressionHandler(IObjectConfigurationRegistry objectConfigurationRegistry, IExpressionParser expressionParser)
        {
            this.objectConfigurationRegistry = objectConfigurationRegistry;
            this.expressionParser = expressionParser;
        }

        public void Handle(IDependencyInjector currentInjector, Expression currentExpression)
        {
            var newExpression = (NewExpression)currentExpression;

            var nestableObjectConfiguration = currentInjector.SelectNestableObjectConfiguration(newExpression.Constructor.DeclaringType);

            foreach (var argument in newExpression.Arguments)
            {
                expressionParser.Parse(
                    new NestingInstantiationDependencyInjector(objectConfigurationRegistry,
                                                               nestableObjectConfiguration,
                                                               argument.Type),
                    argument);
            }
        }
    }
}